#if ORACLE
using System;
using System.Diagnostics;
using System.Reflection;

using NHibernate;
using NHibernate.Cfg;
using System.Collections;
using System.Data;
using System.Data.OracleClient;
using NHibernate.Engine;
using NHibernate.Dialect;

namespace TopSharp.DatabaseUtil
{
	/// <summary>
	/// 支持HQL的 Create Update Find IList 相当于dao
	/// 支持HQL的单独执行 
	/// 支持SQL
	/// 支持对象的直接存储 首先对象必须是跟数据库保持一致
	/// </summary>
	public class HQLHelper
	{
        private static ISessionFactory Session = (new Configuration()).Configure().BuildSessionFactory();

		private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
		private static Hashtable  cmdCache = Hashtable.Synchronized(new Hashtable());
		/// <summary>
		/// 相关字符串
		/// </summary>
		/// public static String ConnectionString = SessionManager.CurrentSession.Connection.ConnectionString;
		
		/// <summary>
		/// Retrieve cached parameters
		/// </summary>
		/// <param name="cacheKey">key used to lookup parameters</param>
		/// <returns>Cached SqlParamters array</returns>
        public static OracleParameter[] GetCachedParameters(string cacheKey) 
		{
			OracleParameter[] cachedParms = (OracleParameter[])parmCache[cacheKey];
			
			if (cachedParms == null)
				return null;
			
			OracleParameter[] clonedParms = new OracleParameter[cachedParms.Length];

			for (int i = 0, j = cachedParms.Length; i < j; i++)
				clonedParms[i] = (OracleParameter)((ICloneable)cachedParms[i]).Clone();

			return clonedParms;
		}

		/// <summary>
		/// add parameter array to the cache
		/// </summary>
		/// <param name="cacheKey">Key to the parameter cache</param>
		/// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params OracleParameter[] cmdParms) 
		{
			parmCache[cacheKey] = cmdParms;
		}


		/// <summary>
		/// Retrieve cached parameters
		/// </summary>
		/// <param name="cacheKey">key used to lookup parameters</param>
		/// <returns>Cached SqlParamters array</returns>
        public static OracleCommand GetCmd(string cacheKey) 
		{
            OracleCommand cachedCmd = (OracleCommand)cmdCache[cacheKey];
			
			if (cachedCmd == null)
				return null;

            return (OracleCommand)((ICloneable)cachedCmd).Clone();
		}

		/// <summary>
		/// add parameter array to the cache
		/// </summary>
		/// <param name="cacheKey">Key to the parameter cache</param>
		/// <param name="cmdParms">an array of SqlParamters to be cached</param>
		public static void CacheCmd(string cacheKey, object Value) 
		{
			cmdCache[cacheKey] = Value;
		}

		/// <summary>
		/// This method is used to attach array of OracleParameters to a OracleCommand.
		/// 
		/// This method will assign a value of DbNull to any parameter with a direction of
		/// InputOutput and a value of null.  
		/// 
		/// This behavior will prevent default values from being used, but
		/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
		/// where the user provided no input value.
		/// </summary>
		/// <param name="command">The command to which the parameters will be added</param>
		/// <param name="commandParameters">An array of OracleParameters to be added to command</param>
        private static void AttachParameters(OracleCommand command, OracleParameter[] commandParameters)
		{
			if( command == null ) throw new ArgumentNullException( "command" );
			if( commandParameters != null )
			{				
				foreach (OracleParameter p in commandParameters)
				{
					if( p != null )
					{
						// Check for derived output value with no value assigned
						if ( ( p.Direction == ParameterDirection.InputOutput || 
							p.Direction == ParameterDirection.Input ) && 
							(p.Value == null))
						{
							p.Value = DBNull.Value;
						}
						command.Parameters.Add(p);
					}
				}
			}
		}
		/// <summary>
		/// 执行sql语句
		/// 如果带事务，一定要用这个函数执行
		/// </summary>
		/// <param name="sql">直接执行sql语句</param>
		/// <returns></returns>
        public static int ExecuteNonQuery(CommandType commandType, string commandText, params OracleParameter[] commandParameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();

				OracleCommand cmd = (OracleCommand)session.Connection.CreateCommand();
				cmd.CommandText = commandText;
				cmd.CommandType = commandType;

				AttachParameters(cmd , commandParameters);

				if(session.Transaction != null)
					session.Transaction.Enlist(cmd);
			
				return cmd.ExecuteNonQuery();
			}
		}

		/// <summary>
		/// 根据主键取得对应的实体对象
		/// </summary>
		/// <param name="sC_ID">ID 主键</param>
		/// <returns> a Object instance </returns>
		public static object Find(object ID ,Type t)
		{
			try
			{
				using(ISession session = Session.OpenSession())
				{
					//DurationManage.Add();
					return session.Get(t,ID);
				}
			}
			catch(Exception e)
			{
				string rr=e.Message;
				return null;
			}
		}

		/// <summary>
		/// Add 一个对象
		/// </summary>
		/// <param name="shouChang">a Object instance</param>
		/// <returns> a Object instance </returns>
		public static object Create(object Model)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				session.Save(Model);
				session.Flush();
				return Model;
			}
		}

		/// <summary>
		/// 更新一个对象
		/// </summary>
		/// <param name="shouChang">a Object instance</param>
		public static void Update(Object Model)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				session.Update(Model);
				session.Flush();
			}
		}

		/// <summary>
		/// Delete 一个对象
		/// </summary>
		/// <param name="ID">ID 主键</param>
        public static void Delete(Object ID, Type t)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				session.Delete(session.Load(t,ID));
				session.Flush();
			}
		}

		/// <summary>
		/// 用Hql语句Return所有数据 .外部调用
		/// </summary>
		/// <param name="hql"></param>
		/// <param name="parameters"></param>
		/// <returns></returns>
		public static IList ExecuteIList(string hql, params object[] parameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				IQuery query = session.CreateQuery(hql);

				if (parameters != null)
					for (int i=0; i < parameters.Length; i++)
						query.SetParameter(i, parameters[i]);

				return query.List();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="commandType"></param>
		/// <param name="commandText">sql</param>
		/// <param name="commandParameters"></param>
		/// <returns></returns>
        public static object ExecuteScalar(CommandType commandType, string commandText, params OracleParameter[] commandParameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
                OracleCommand cmd = (OracleCommand)session.Connection.CreateCommand();
				cmd.CommandText = commandText;
				cmd.CommandType = commandType;

				AttachParameters(cmd , commandParameters);

				if(session.Transaction != null)
					session.Transaction.Enlist(cmd);
			
				return cmd.ExecuteScalar();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="commandType"></param>
		/// <param name="commandText"></param>
		/// <param name="commandParameters"></param>
		/// <returns></returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText, params OracleParameter[] commandParameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				OracleCommand cmd = (OracleCommand)session.Connection.CreateCommand();
				cmd.CommandText = commandText;
				cmd.CommandType = commandType;

				AttachParameters(cmd , commandParameters);

				if(session.Transaction != null)
					session.Transaction.Enlist(cmd);
    			
				// Create the DataAdapter & DataSet
				using( OracleDataAdapter da = new OracleDataAdapter(cmd) )
				{
					DataSet ds = new DataSet();

					// Fill the DataSet using default values for DataTable names, etc
					da.Fill(ds);
				
					// Detach the OracleParameters from the command object, so they can be used again
					cmd.Parameters.Clear();

					return ds;
				}	
			}
		}
		
		/// <summary>
		/// This method assigns dataRow column values to an array of OracleParameters
		/// </summary>
		/// <param name="commandParameters">Array of OracleParameters to be assigned values</param>
		/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
		static void AssignParameterValues(OracleCommand command , DataRow dataRow)
		{
			if (dataRow == null) 
			{
				// Do nothing if we get no data
				return;
			}

			int i = 0;
			// Set the parameters values
			for(; i < command.Parameters.Count ; )
			{
				// Check the parameter name
				if( command.Parameters[i].ParameterName == null || 
					command.Parameters[i].ParameterName.Length <= 1 )
					throw new Exception( 
						string.Format( 
						"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.", 
						i, command.Parameters[i].ParameterName ) );
				//if (dataRow.Table.Columns.IndexOf(command.Parameters[i].ParameterName.Substring(1)) != -1)
				command.Parameters[i].Value = dataRow[i];
				i++;
				
			}
		}

        /// <summary>
        /// 保留原始分页
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <param name="firstIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteDatasetPager(CommandType commandType, string commandText, int firstIndex, int pageSize, params OracleParameter[] commandParameters)
        {
            using (ISession session = Session.OpenSession())
            {
                OracleCommand cmd = (OracleCommand)session.Connection.CreateCommand();
                cmd.CommandText = commandText;
                cmd.CommandType = commandType;

                AttachParameters(cmd, commandParameters);

                if (session.Transaction != null)
                    session.Transaction.Enlist(cmd);

                // Create the DataAdapter & DataSet
                using (OracleDataAdapter da = new OracleDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    // Fill the DataSet using default values for DataTable names, etc
                    da.Fill(ds, firstIndex, pageSize, "SQLPager");

                    // Detach the OracleParameters from the command object, so they can be used again
                    cmd.Parameters.Clear();

                    // Return the dataset
                    return ds;
                }
            }
        }
	}
}
#endif
#if MYSQL
using System;
using System.Diagnostics;
using System.Reflection;

using NHibernate;
using NHibernate.Cfg;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using NHibernate.Engine;
using NHibernate.Dialect;
using ForeignAffairsSystem.Models;


namespace ForeignAffairsSystem.ORM_NHibernate
{
    /// <summary>
    /// 支持HQL的 Create Update Find IList 相当于dao
    /// 支持HQL的单独执行 
    /// 支持SQL
    /// 支持对象的直接存储 首先对象必须是跟数据库保持一致
    /// </summary>
    public class HQLHelper
    {
        public static ISessionFactory Session = (new Configuration()).Configure().BuildSessionFactory();

        //static ISessionManager Session = (ISessionManager)Container.instance.Kernel[typeof(ISessionManager)];

        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        private static Hashtable cmdCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// 相关字符串
        /// </summary>
        /// public static String ConnectionString = SessionManager.CurrentSession.Connection.ConnectionString;

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static MySqlParameter[] GetCachedParameters(string cacheKey)
        {
            MySqlParameter[] cachedParms = (MySqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            MySqlParameter[] clonedParms = new MySqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (MySqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params MySqlParameter[] cmdParms)
        {
            parmCache[cacheKey] = cmdParms;
        }


        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static MySqlCommand GetCmd(string cacheKey)
        {
            MySqlCommand cachedCmd = (MySqlCommand)cmdCache[cacheKey];

            if (cachedCmd == null)
                return null;

            return (MySqlCommand)((ICloneable)cachedCmd).Clone();
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheCmd(string cacheKey, object Value)
        {
            cmdCache[cacheKey] = Value;
        }

        /// <summary>
        /// This method is used to attach array of MySqlParameters to a MySqlCommand.
        /// 
        /// This method will assign a value of DbNull to any parameter with a direction of
        /// InputOutput and a value of null.  
        /// 
        /// This behavior will prevent default values from being used, but
        /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
        /// where the user provided no input value.
        /// </summary>
        /// <param name="command">The command to which the parameters will be added</param>
        /// <param name="commandParameters">An array of MySqlParameters to be added to command</param>
        private static void AttachParameters(MySqlCommand command, MySqlParameter[] commandParameters)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (commandParameters != null)
            {
                foreach (MySqlParameter p in commandParameters)
                {
                    if (p != null)
                    {
                        // Check for derived output value with no value assigned
                        if ((p.Direction == ParameterDirection.InputOutput ||
                            p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        command.Parameters.Add(p);
                    }
                }
            }
        }
        /// <summary>
        /// 执行sql语句
        /// 如果带事务，一定要用这个函数执行
        /// </summary>
        /// <param name="sql">直接执行sql语句</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();

                MySqlCommand cmd = (MySqlCommand)session.Connection.CreateCommand();
                cmd.CommandText = commandText;
                cmd.CommandType = commandType;

                AttachParameters(cmd, commandParameters);

                if (session.Transaction != null)
                    session.Transaction.Enlist(cmd);

                return cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 根据主键取得对应的实体对象
        /// </summary>
        /// <param name="sC_ID">ID 主键</param>
        /// <returns> a Object instance </returns>
        public static object Find(object ID, Type t)
        {
            try
            {
                using (ISession session = Session.OpenSession())
                {
                    //DurationManage.Add();
                    return session.Get(t, ID);
                }
            }
            catch (Exception e)
            {
                string rr = e.Message;
                return null;
            }
        }

        /// <summary>
        /// Add 一个对象
        /// </summary>
        /// <param name="shouChang">a Object instance</param>
        /// <returns> a Object instance </returns>
        public static object Create(object Model)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                session.Save(Model);
                session.Flush();
                return Model;
            }
        }

        /// <summary>
        /// 更新一个对象
        /// </summary>
        /// <param name="shouChang">a Object instance</param>
        public static void Update(Object Model)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                session.Update(Model);
                session.Flush();
            }
        }

        /// <summary>
        /// Delete 一个对象
        /// </summary>
        /// <param name="ID">ID 主键</param>
        public static void Delete(Object ID, Type t)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                session.Delete(session.Load(t, ID));
                session.Flush();
            }
        }

        /// <summary>
        /// 用Hql语句Return所有数据 .外部调用
        /// </summary>
        /// <param name="hql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IList ExecuteTopQuery(string hql, int iMaxRows, params object[] parameters)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                IQuery query = session.CreateQuery(hql);

                query.SetMaxResults(iMaxRows);

                if (parameters != null)
                    for (int i = 0; i < parameters.Length; i++)
                        query.SetParameter(i, parameters[i]);

                return query.List();
            }
        }

        /// <summary>
        /// 用Hql语句Return所有数据 .外部调用
        /// </summary>
        /// <param name="hql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IList ExecuteIList(string hql, params object[] parameters)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                IQuery query = session.CreateQuery(hql);

                if (parameters != null)
                    for (int i = 0; i < parameters.Length; i++)
                        query.SetParameter(i, parameters[i]);

                return query.List();
            }
        }

        /// <summary>
        /// 用Hql语句Return所有数据 .外部调用
        /// </summary>
        /// <param name="hql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IList<T> ExecuteIList<T>(string hql, params object[] parameters) where T : EntityBase
        {
            using (ISession session = Session.OpenSession())
            {
                IQuery query = session.CreateQuery(hql);

                if (parameters != null)
                    for (int i = 0; i < parameters.Length; i++)
                        query.SetParameter(i, parameters[i]);

                return query.List<T>();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="commandText">sql</param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static object ExecuteScalar(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                MySqlCommand cmd = (MySqlCommand)session.Connection.CreateCommand();
                cmd.CommandText = commandText;
                cmd.CommandType = commandType;

                AttachParameters(cmd, commandParameters);

                if (session.Transaction != null)
                    session.Transaction.Enlist(cmd);

                return cmd.ExecuteScalar();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            using (ISession session = Session.OpenSession())
            {
                //DurationManage.Add();
                MySqlCommand cmd = (MySqlCommand)session.Connection.CreateCommand();
                cmd.CommandText = commandText;
                cmd.CommandType = commandType;

                AttachParameters(cmd, commandParameters);

                if (session.Transaction != null)
                    session.Transaction.Enlist(cmd);

                // Create the DataAdapter & DataSet
                using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();

                    // Fill the DataSet using default values for DataTable names, etc
                    da.Fill(ds);

                    // Detach the MySqlParameters from the command object, so they can be used again
                    cmd.Parameters.Clear();

                    return ds;
                }
            }
        }

        /// <summary>
        /// This method assigns dataRow column values to an array of MySqlParameters
        /// </summary>
        /// <param name="commandParameters">Array of MySqlParameters to be assigned values</param>
        /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
        static void AssignParameterValues(MySqlCommand command, DataRow dataRow)
        {
            if (dataRow == null)
            {
                // Do nothing if we get no data
                return;
            }

            int i = 0;
            // Set the parameters values
            for (; i < command.Parameters.Count; )
            {
                // Check the parameter name
                if (command.Parameters[i].ParameterName == null ||
                    command.Parameters[i].ParameterName.Length <= 1)
                    throw new Exception(
                        string.Format(
                        "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
                        i, command.Parameters[i].ParameterName));
                //if (dataRow.Table.Columns.IndexOf(command.Parameters[i].ParameterName.Substring(1)) != -1)
                command.Parameters[i].Value = dataRow[i];
                i++;

            }
        }

        /// <summary>
        /// 保留原始分页
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <param name="firstIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteDatasetPager(CommandType commandType, string commandText, int firstIndex, int pageSize, params MySqlParameter[] commandParameters)
        {
            using (ISession session = Session.OpenSession())
            {
                MySqlCommand cmd = (MySqlCommand)session.Connection.CreateCommand();
                cmd.CommandText = commandText;
                cmd.CommandType = commandType;

                AttachParameters(cmd, commandParameters);

                if (session.Transaction != null)
                    session.Transaction.Enlist(cmd);

                // Create the DataAdapter & DataSet
                using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    // Fill the DataSet using default values for DataTable names, etc
                    da.Fill(ds, firstIndex, pageSize, "SQLPager");

                    // Detach the MySqlParameters from the command object, so they can be used again
                    cmd.Parameters.Clear();

                    // Return the dataset
                    return ds;
                }
            }
        }
        /// <summary>
        /// 功能: 执行事务的多个sql语句
        /// [2011-07-09 20:16:54 战东耀]<para />
        /// </summary>
        /// <param name="sSQL"></param>
        /// <returns></returns>
        public static string SQLCommitByTrans(string[] sSQL)
        {
            string sReturn = "";

            using (ISession session = Session.OpenSession())
            {
                using (ITransaction tx = session.BeginTransaction())
                {
                    try
                    {
                        //一些保存、更新、删除等操作
                        MySqlCommand dataCommand = (MySqlCommand)session.Connection.CreateCommand();
                        tx.Enlist(dataCommand);
                        for (int i = 0; i < sSQL.Length; i++)
                        {
                            dataCommand.CommandText = sSQL[i];
                            dataCommand.ExecuteNonQuery();
                        }
                        tx.Commit();
                    }
                    catch (HibernateException ex)
                    {
                        tx.Rollback();
                        sReturn = ex.Message;
                    }
                }
            }
            return sReturn;
        }
    }
}
#endif
#if SQLSERVER
using System;
using System.Diagnostics;
using System.Reflection;

using NHibernate;
using NHibernate.Cfg;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using NHibernate.Engine;
using NHibernate.Dialect;
using GCT.Entity;

namespace GCT.DAL
{
	/// <summary>
	/// 支持HQL的 Create Update Find IList 相当于dao
	/// 支持HQL的单独执行 
	/// 支持SQL
	/// 支持对象的直接存储 首先对象必须是跟数据库保持一致
	/// </summary>
	public class HQLHelper
	{
        public static ISessionFactory Session;// = (new Configuration()).Configure().BuildSessionFactory();

        static HQLHelper()
        {
            Session = (new Configuration()).Configure().BuildSessionFactory();
        }

		//static ISessionManager Session = (ISessionManager)Container.instance.Kernel[typeof(ISessionManager)];

		private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
		private static Hashtable  cmdCache = Hashtable.Synchronized(new Hashtable());

		/// <summary>
		/// 相关字符串
		/// </summary>
		/// public static String ConnectionString = SessionManager.CurrentSession.Connection.ConnectionString;
		
		/// <summary>
		/// Retrieve cached parameters
		/// </summary>
		/// <param name="cacheKey">key used to lookup parameters</param>
		/// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey) 
		{
			SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
			
			if (cachedParms == null)
				return null;
			
			SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

			for (int i = 0, j = cachedParms.Length; i < j; i++)
				clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

			return clonedParms;
		}

		/// <summary>
		/// add parameter array to the cache
		/// </summary>
		/// <param name="cacheKey">Key to the parameter cache</param>
		/// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] cmdParms) 
		{
			parmCache[cacheKey] = cmdParms;
		}


		/// <summary>
		/// Retrieve cached parameters
		/// </summary>
		/// <param name="cacheKey">key used to lookup parameters</param>
		/// <returns>Cached SqlParamters array</returns>
        public static SqlCommand GetCmd(string cacheKey) 
		{
            SqlCommand cachedCmd = (SqlCommand)cmdCache[cacheKey];
			
			if (cachedCmd == null)
				return null;

            return (SqlCommand)((ICloneable)cachedCmd).Clone();
		}

		/// <summary>
		/// add parameter array to the cache
		/// </summary>
		/// <param name="cacheKey">Key to the parameter cache</param>
		/// <param name="cmdParms">an array of SqlParamters to be cached</param>
		public static void CacheCmd(string cacheKey, object Value) 
		{
			cmdCache[cacheKey] = Value;
		}

		/// <summary>
		/// This method is used to attach array of SqlParameters to a SqlCommand.
		/// 
		/// This method will assign a value of DbNull to any parameter with a direction of
		/// InputOutput and a value of null.  
		/// 
		/// This behavior will prevent default values from being used, but
		/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
		/// where the user provided no input value.
		/// </summary>
		/// <param name="command">The command to which the parameters will be added</param>
		/// <param name="commandParameters">An array of SqlParameters to be added to command</param>
        private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
		{
			if( command == null ) throw new ArgumentNullException( "command" );
			if( commandParameters != null )
			{				
				foreach (SqlParameter p in commandParameters)
				{
					if( p != null )
					{
						// Check for derived output value with no value assigned
						if ( ( p.Direction == ParameterDirection.InputOutput || 
							p.Direction == ParameterDirection.Input ) && 
							(p.Value == null))
						{
							p.Value = DBNull.Value;
						}
						command.Parameters.Add(p);
					}
				}
			}
		}
		/// <summary>
		/// 执行sql语句
		/// 如果带事务，一定要用这个函数执行
		/// </summary>
		/// <param name="sql">直接执行sql语句</param>
		/// <returns></returns>
        public static int ExecuteNonQuery(CommandType commandType, string commandText, params SqlParameter[] commandParameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();

				SqlCommand cmd = (SqlCommand)session.Connection.CreateCommand();
				cmd.CommandText = commandText;
				cmd.CommandType = commandType;

				AttachParameters(cmd , commandParameters);

				if(session.Transaction != null)
					session.Transaction.Enlist(cmd);
			
				return cmd.ExecuteNonQuery();
			}
		}

		/// <summary>
		/// 根据主键取得对应的实体对象
		/// </summary>
		/// <param name="sC_ID">ID 主键</param>
		/// <returns> a Object instance </returns>
		public static object Find(object ID ,Type t)
		{
			try
			{
				using(ISession session = Session.OpenSession())
				{
					//DurationManage.Add();
					return session.Get(t,ID);
				}
			}
			catch(Exception e)
			{
				string rr=e.Message;
				return null;
			}
		}

		/// <summary>
		/// Add 一个对象
		/// </summary>
		/// <param name="shouChang">a Object instance</param>
		/// <returns> a Object instance </returns>
		public static object Create(object Model)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				session.Save(Model);
				session.Flush();
				return Model;
			}
		}

		/// <summary>
		/// 更新一个对象
		/// </summary>
		/// <param name="shouChang">a Object instance</param>
		public static void Update(Object Model)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				session.Update(Model);
				session.Flush();
			}
		}

		/// <summary>
		/// Delete 一个对象
		/// </summary>
		/// <param name="ID">ID 主键</param>
        public static void Delete(Object ID, Type t)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				session.Delete(session.Load(t,ID));
				session.Flush();
			}
		}

		/// <summary>
		/// 用Hql语句Return所有数据 .外部调用
		/// </summary>
		/// <param name="hql"></param>
		/// <param name="parameters"></param>
		/// <returns></returns>
		public static IList ExecuteIList(string hql, params object[] parameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				IQuery query = session.CreateQuery(hql);

				if (parameters != null)
					for (int i=0; i < parameters.Length; i++)
						query.SetParameter(i, parameters[i]);

				return query.List();
			}
		}

        /// <summary>
        /// 用Hql语句Return所有数据 .外部调用
        /// </summary>
        /// <returns></returns>
        public static IList<T> ExecuteIList<T>() where T : EntityBase
        {
            string hql = "from " + typeof(T).ToString();
            return ExecuteIList<T>(hql, null);
        }

        /// <summary>
        /// 用Hql语句Return所有数据 .外部调用
        /// </summary>
        /// <param name="hql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IList<T> ExecuteIList<T>(string hql, params object[] parameters) where T:EntityBase
        {
            using (ISession session = Session.OpenSession())
            {
                IQuery query = session.CreateQuery(hql);

                if (parameters != null)
                    for (int i = 0; i < parameters.Length; i++)
                        query.SetParameter(i, parameters[i]);

                return query.List<T>();
            }
        }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="commandType"></param>
		/// <param name="commandText">sql</param>
		/// <param name="commandParameters"></param>
		/// <returns></returns>
        public static object ExecuteScalar(CommandType commandType, string commandText, params SqlParameter[] commandParameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
                SqlCommand cmd = (SqlCommand)session.Connection.CreateCommand();
				cmd.CommandText = commandText;
				cmd.CommandType = commandType;

				AttachParameters(cmd , commandParameters);

				if(session.Transaction != null)
					session.Transaction.Enlist(cmd);
			
				return cmd.ExecuteScalar();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="commandType"></param>
		/// <param name="commandText"></param>
		/// <param name="commandParameters"></param>
		/// <returns></returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText, params SqlParameter[] commandParameters)
		{
			using(ISession session = Session.OpenSession())
			{
				//DurationManage.Add();
				SqlCommand cmd = (SqlCommand)session.Connection.CreateCommand();
				cmd.CommandText = commandText;
				cmd.CommandType = commandType;

				AttachParameters(cmd , commandParameters);

				if(session.Transaction != null)
					session.Transaction.Enlist(cmd);
    			
				// Create the DataAdapter & DataSet
				using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
				{
					DataSet ds = new DataSet();

					// Fill the DataSet using default values for DataTable names, etc
					da.Fill(ds);
				
					// Detach the SqlParameters from the command object, so they can be used again
					cmd.Parameters.Clear();

					return ds;
				}	
			}
		}
		
		/// <summary>
		/// This method assigns dataRow column values to an array of SqlParameters
		/// </summary>
		/// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
		/// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
		static void AssignParameterValues(SqlCommand command , DataRow dataRow)
		{
			if (dataRow == null) 
			{
				// Do nothing if we get no data
				return;
			}

			int i = 0;
			// Set the parameters values
			for(; i < command.Parameters.Count ; )
			{
				// Check the parameter name
				if( command.Parameters[i].ParameterName == null || 
					command.Parameters[i].ParameterName.Length <= 1 )
					throw new Exception( 
						string.Format( 
						"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.", 
						i, command.Parameters[i].ParameterName ) );
				//if (dataRow.Table.Columns.IndexOf(command.Parameters[i].ParameterName.Substring(1)) != -1)
				command.Parameters[i].Value = dataRow[i];
				i++;
				
			}
		}

        /// <summary>
        /// 保留原始分页
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="commandText"></param>
        /// <param name="firstIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecuteDatasetPager(CommandType commandType, string commandText, int firstIndex, int pageSize, params SqlParameter[] commandParameters)
        {
            using (ISession session = Session.OpenSession())
            {
                SqlCommand cmd = (SqlCommand)session.Connection.CreateCommand();
                cmd.CommandText = commandText;
                cmd.CommandType = commandType;

                AttachParameters(cmd, commandParameters);

                if (session.Transaction != null)
                    session.Transaction.Enlist(cmd);

                // Create the DataAdapter & DataSet
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    // Fill the DataSet using default values for DataTable names, etc
                    da.Fill(ds, firstIndex, pageSize, "SQLPager");

                    // Detach the SqlParameters from the command object, so they can be used again
                    cmd.Parameters.Clear();

                    // Return the dataset
                    return ds;
                }
            }
        }
        /// <summary>
        /// 功能: 执行事务的多个sql语句
        /// [2011-07-09 20:16:54 战东耀]<para />
        /// </summary>
        /// <param name="sSQL"></param>
        /// <returns></returns>
        public static string SQLCommitByTrans(string[] sSQL)
        {
            string sReturn = "";

            using (ISession session = Session.OpenSession())
            {
                using (ITransaction tx = session.BeginTransaction())
                {
                    try
                    {
                        //一些保存、更新、删除等操作
                        SqlCommand dataCommand = (SqlCommand)session.Connection.CreateCommand();
                        tx.Enlist(dataCommand);
                        for (int i = 0; i < sSQL.Length; i++)
                        {
                            dataCommand.CommandText = sSQL[i];
                            dataCommand.ExecuteNonQuery();
                        }
                        tx.Commit();
                    }
                    catch (HibernateException ex)
                    {
                        tx.Rollback();
                        sReturn = ex.Message;
                    }
                }
            }
            return sReturn;
        }
	}
}
#endif
